<template lang="pug">
  .clearfix
    Modal(
      width="80%"
      v-model="isShowPayListModal"
      title="确认付款"
      class-name="vertical-center-modal"
    )
      .pl-20.pr-20.bg-white.mb-30
        Table.hasTitle-table.beautiful-table(:columns="setThead" :data="tableData" :stripe="true" ref="demoTable"
          @on-selection-change="handleOnSelectChange"
        )
          template(slot-scope="{ row, index }" slot="action")
            Button.mr-10(type="text" size="small" @click="handleDownLoadAttachment(row)" :disabled="!(row.attachmen && row.attachmen.path)") 附件下载
            //- Button.mr-10(type="text" size="small" @click="handleDownLoadPayAttachmen(row)" :disabled="!(row.payAttachmen && row.payAttachmen.path)") 付款反馈下载
            Button.mr-10(v-if="hasReject && isWorkFlow" type="text" :disabled="row.workFlowStatus == '已完成' ? false : true"  @click="handleShowSendBackModal(row,-1)") 驳回
            //- 社保/公积金/商保/待遇: 1-待申请 2-已申请 3-已付款 4-待付款 -1-已驳回 -2-已退回
            //- 薪资：1-待申请 2-待发放 3-已发放 4-已驳回 5-已退回
            Button.mr-10(v-if="hasReject && !isWorkFlow" type="text" :disabled="(['socialSecurity', 'providentFund', 'commercial', 'daiyuyingfu','daiyushenqing'].indexOf(modalType) != -1 && row.status == 4) || (modalType == 'salary' && row.status == 2) ? false : true" @click="handleShowSendBackModal(row,-1)") 驳回
            Button(v-if="isWorkFlow" type="text" size="small" @click="handleShowAuditDetailModal(row)") 查看审批详情
      .search-form
        Form.ivu-row(ref="formData" :model="formData" :rules="rules" :label-width="130")
          FormItem.form-item.ivu-col.pr-20(v-for="(item, index) of formItem" :label="item.label" :key="index" :class="item.style" :prop="item.prop")
            template(v-if="item.type === 'input'")
              Input(v-model="formData[item.model]" :placeholder="item.placeholder" :disabled="item.isDisabled")
            template(v-if="item.type === 'select'")
              Select(v-model="formData[item.model]" :placeholder="item.placeholder" clearable filterable)
                Option(
                  v-for="(c_item, index) in arrListDown[item.options]"
                  :value="c_item.bankName"
                  :key="index"
                ) {{ c_item.bankName }}
            template(v-if="item.type === 'datePicker'")
              DatePicker.w-100(v-model="formData[item.model]" placeholder="请选择" type="date" format="yyyy-MM-dd" @on-change="handleChangeDatePicker(item.model, $event)")
            template(v-if="item.type === 'upload'")
              Upload.pull-left.mb-5(
                ref="upload"
                :show-upload-list="false"
                accept=".doc, .docx, .xls, .xlsx, .pptx, .jpg, .jpeg, .png, .rar"
                :action="baseUrl + 'api/FinanceSSPayable/AnnexUpload?categoryName=确认付款附件'"
                :on-success="uploadSuccess"
                :headers="headers"
                :max-size="10 * 1024"
                :on-exceeded-size="handleMaxSizeTen"
              )
                Button.download-btn(type="info") 附件上传
              div.pull-left.line-h-32.ml-10(v-if="fileObj && fileObj.Id")
                span.mr-10 {{fileObj.Name}}
                Icon.cursor-pointer.text-error(type="ios-close-circle" @click="removeFile")

      .clearfix(slot="footer")
        Button(type="text" @click="cancel") 取消
        Button(type="primary" @click="confirmPay" :loading="!isCanSubmit" :disabled="!selectedIdArr.length") 确定
    //- 退回弹窗
    SendBackModal(ref="SendBackModal" @query='query')
</template>

<script>
import { SalaryPayableBillApi } from '@/api/SalaryPayableBill.api.js'
import { FinanceSSPayableApi } from '@/api/FinanceSSPayable.api.js'
import { FinancePFPayableApi } from '@/api/FinancePFPayable.api.js'
import { FinanceCPayableApi } from '@/api/FinanceCPayable.api.js'
import { OrganizationBankApi } from '@/api/OrganizationBank.api.js'
import { FinanceTreatmentPayableApi } from '@/api/FinanceTreatmentPayable.api.js'
import SendBackModal from "../publicModal/SendBackModal.vue"
import { Common } from '@/utils/common.js'
import _cloneDeep from 'clone-deep'
import { PayListThead } from './tableHead'
import dataApi from '@/api/data.js'
import Cookies from 'js-cookie'
export default {
  name: '',

  props: {
  },

  computed: {
    actionArr() {
      let arr = this.$store.state.user.actionAccess.map(item => {
        return item.code;
      });
      return arr;
    },
    hasReject() {
      return this.actionArr.indexOf("Reject") > -1;
    },

    isWorkFlow () {
      const workFlow = (JSON.parse(localStorage.getItem('clientLoginInfo'))).data.workFlow == 'true' ? true : false
      return workFlow
    },
    setThead () {
      if (this.modalType === 'daiyuyingfu' || this.modalType === 'daiyushenqing') {
        this.thead[3].title = '账号名称'
        this.thead[3].key = 'accountName'
      }
      if (this.isWorkFlow) {
        return this.thead.slice(0, this.thead.length + 1) 
      } else {
        return [...this.thead.slice(0, 2), ...this.thead.slice(3, this.thead.length + 1)]
      }
    },
    // Reject
  },

  components: {
    SendBackModal
  },

  data () {
    const validateAmount = (rule, value, callback) => {
      if (value > this.queryAmount) {
        callback(new Error('付款金额不能大于剩余应付金额'))
      } else {
        callback()
      }
    }

    return {
      headers: {
        'Authorization': 'Bearer ' + Cookies.get('clientToken')
      },
      baseUrl: baseUrl,
      isShowPayListModal: false,
      thead: _cloneDeep(PayListThead),
      tableData: [],
      tableComone: {
        pageIndex: 1, // 页码
        totalRows: 0, // 总条数
        pageSize: 10, // 当前页面展示条数
        total: 0, // 应付总计
      },
      selectedArr: [],
      selectedIdArr: [],
      formData: {
        type: null,
        amount: '',
        payDate: new Date(),
        bankName: '',
        periodYear: '',
        periodMonth: '',
        annexId: null
      },
      formItem: [
        { type: 'input', label: '付款金额', placeholder: '请输入付款金额', prop: 'amount', model: 'amount', style: 'ivu-col-span-12', files: [], isDisabled: true },
        { type: 'datePicker', label: '付款时间', placeholder: '请选择付款时间', prop: 'payDate', model: 'payDate', style: 'ivu-col-span-12' },
        { type: 'select', label: '付款银行', placeholder: '请选择付款银行', prop: 'bankName', model: 'bankName', style: 'ivu-col-span-12', options: 'bankList' },
        { type: 'upload', label: '付款反馈上传：', placeholder: '付款反馈上传', prop: 'annexId', model: 'annexId', style: 'ivu-col-span-12' },
      ],
      rules: {
        amount: [
          { required: true, message: '请输入付款金额' },
          { validator: validateAmount, trigger: 'blur' }
        ],
        payDate: [
          { required: true, message: '请选择付款时间' }
        ],
        bankName: [
          { required: true, message: '请选择付款银行' }
        ],
      },
      arrListDown: {
        bankList: []
      },
      isCanSubmit: true,
      salaryParams: {
        salaryMonth: null,
        customerGUID: null,
        customerName: null,
        sendDate: null
      },
      socialSecurityParams: {
        periodYear: null,
        periodMonth: null,
        securityNo: null,
        socialSecurityNo: null,
        total: null,
        payableTotal: null
      },
      providentFundParams: {
        periodYear: null,
        periodMonth: null,
        securityNo: null,
        providentFundNo: null,
        total: null,
        payableTotal: null
      },
      commercialParams: {
        periodYear: null,
        periodMonth: null,
        securityNo: null,
        commercialNo: null,
        total: null,
        payableTotal: null,
        commercialID: null
      },
      daiyuParams: {
        TPBillsID: null,
        // PayableTotal: null,
        // Amount: null,
        // PayDate: null,
        // BankName: null,
        // PayDetailIDs: [],
        // IsPay: true
      },
      modalType: null,
      fileObj: null,
    }
  },

  watch: {
  },

  mounted () {
    this.getBankList()
  },

  methods: {
    // 获取银行账号下拉列表
    async getBankList() {
      var params = {
        id: JSON.parse(localStorage.getItem('clientLoginInfo')).data.companyId
      }
      let res = await OrganizationBankApi.getBankList(params)
      console.log("获取银行账号下拉列表res: ", res)
      if (res.status === 200 && res.data.success) {
        this.arrListDown.bankList = res.data.data
      } else {
      }
      this.loading = false
    },

    /**
     * 分页查询接口
     * @param {Object} obj {pageIndex, pageSize}
     */
    async query (row) {
      console.log('♥ 获取确认付款列表 ', row)
      this.selectedArr = []
      this.selectedIdArr = []
      this.$refs.formData.resetFields()

      this.parentRow = row
      console.log(this.parentRow,'this.parentRow')
      var params = {
        PeriodYear: row.periodYear,
        PeriodMonth: row.periodMonth,
        IsPay: true,
      }
      var serverApi
      if (this.modalType === 'salary') {
        serverApi = SalaryPayableBillApi
      } else if (this.modalType === 'socialSecurity') {
        params.SecurityNo = row.socialSecurityNo
        serverApi = FinanceSSPayableApi
      } else if  (this.modalType === 'providentFund') {
        params.SecurityNo = row.providentFundNo
        serverApi = FinancePFPayableApi
      } else if  (this.modalType === 'commercial') {
        params.SecurityNo = row.commercialNo
        params.CommercialID = row.commercialID
        serverApi = FinanceCPayableApi
      } else if (this.modalType === 'daiyuyingfu' || this.modalType === 'daiyushenqing') {
        params.TPBillsID = row.id
        serverApi = FinanceTreatmentPayableApi
        console.log('serverApi: ', FinanceTreatmentPayableApi)
      }
      let res = await serverApi.getPayList(params)
      console.log('付款信息列表res: ', res)
      if (res.status === 200 && res.data.success) {
        if (this.isWorkFlow) {
          this.tableData = res.data.data.map(item => {
            return {...item, _disabled: item.workFlowStatus == '已完成' ? false : true}
          })
        } else {
          this.tableData = res.data.data
        }
      } else {
        this.tableData = []
      }
      this.loading = false
    },

    /**
     * 分页页码变动
     * @param {Number} val pageIndex
     */
    onChangePage (val) {
      this.tableComone.pageIndex = val
      this.query()
    },
    /**
     * 分页页码变动
     * @param {Number} val pageSize
     */
    onpageSizeChange (val) {
      this.tableComone.pageIndex = 1
      this.tableComone.pageSize = val
      this.query()
    },

    // 表格选择操作
    handleOnSelectChange (value) {
      let amt = 0
      this.selectedArr = value.map((item) => {
        amt += item.applyTotal
        return { id: item.id, name: item.name }
      })
      this.selectedIdArr = value.map((item) => {
        return item.id
      })
      console.log('列表勾选数组1', this.selectedArr)
      console.log('列表勾选数组2', this.selectedIdArr)
      console.log('amt', amt)
      this.formData.amount = amt
    },

    cancel () {
      this.isShowPayListModal = false
    },

    show () {
      this.isShowPayListModal = true
      this.fileObj = null
    },

    // 日期选择
    handleChangeDatePicker (model, val) {
      console.log('model: ', model, ', val: ', val)
      if (val) {
        this.formData[model] = this.$moment(val).format('YYYY-MM-DD')
      } else {
        this.formData[model] = null
      }
    },

    handleShowSendBackModal (row,backType) {
      console.log('点击驳回弹窗时 this.modalType：', this.modalType)
      this.$refs.SendBackModal.modalType = this.modalType
      this.$refs.SendBackModal.parentRow = this.parentRow
      this.$refs.SendBackModal.show(row,backType)
    },

    // 工资付款确认
    async confirmPay () {
      var params = {
        Amount: this.formData.amount,
        PayDate: this.formData.payDate,
        BankName: this.formData.bankName,
        PayDetailIDs: this.selectedIdArr,
        annexId: this.formData.annexId
      }
      var mergeParams = {}
      var serverApi
      if (this.modalType === 'salary') {
        serverApi = SalaryPayableBillApi
        mergeParams = {...params, ...this.salaryParams}
      } else if (this.modalType === 'socialSecurity') {
        this.socialSecurityParams.securityNo = this.socialSecurityParams.socialSecurityNo
        this.socialSecurityParams.payableTotal = this.socialSecurityParams.total
        mergeParams = {...params, ...this.socialSecurityParams}
        serverApi = FinanceSSPayableApi
      } else if  (this.modalType === 'providentFund') {
        this.providentFundParams.securityNo = this.providentFundParams.providentFundNo
        this.providentFundParams.payableTotal = this.providentFundParams.total
        mergeParams = {...params, ...this.providentFundParams}
        serverApi = FinancePFPayableApi
      } else if  (this.modalType === 'commercial') {
        this.commercialParams.securityNo = this.commercialParams.commercialNo
        this.commercialParams.payableTotal = this.commercialParams.total
        mergeParams = {...params, ...this.commercialParams}
        serverApi = FinanceCPayableApi
      } else if  (this.modalType === 'daiyuyingfu' || this.modalType === 'daiyushenqing') {
        this.daiyuParams.TPBillsID = this.parentRow.id
        mergeParams = {...params, ...this.daiyuParams}
        // console.log('this.daiyuParams: ', this.daiyuParams)
        serverApi = FinanceTreatmentPayableApi
      }
      console.log('mergeParams: ', mergeParams)

      this.$refs.formData.validate((valid) => {
        if (valid) {
          if (this.selectedIdArr && this.selectedIdArr.length) {
            serverApi.confirmPay(mergeParams).then(res => {
              if (res.status === 200 && res.data.success) {
                this.$Message.success(res.data.message)
                this.$emit('query')
                this.isShowPayListModal = false
              } else {
                this.$Message.error({
                  content: res.data.message,
                  duration: 10,
                  closable: true
                })
              }
            })
          } else {
            this.$Message.warning({
              content: '付款金额不能为空',
              duration: 10,
              closable: true
            })
          }
        }
      })
    },

    // 查看审批详情
    handleShowAuditDetailModal (row) {
      console.log('查看审批详情')
      this.$emit('handleShowAuditDetailModal', row)
    },

    // 附件下载
    handleDownLoadAttachment (row) {
      if (row.attachmen && row.attachmen.path) {
        let str = row.attachmen.path
        console.log('附件下载: ', str.substring(str.indexOf('\Content') - 1))
        let path = str.substring(str.indexOf('\Content') - 1)
        window.open(path, '_blank')
      } else {
        this.$Message.warning({
          content: '不能下载',
          duration: 10,
          closable: true
        })
      }
    },

    // 付款反馈下载
    handleDownLoadPayAttachmen (row) {
      if (row.payAttachmen && row.payAttachmen.path) {
        let str = row.payAttachmen.path
        console.log('付款反馈下载: ', str.substring(str.indexOf('\Content') - 1))
        let path = str.substring(str.indexOf('\Content') - 1)
        window.open(path, '_blank')
      } else {
        this.$Message.warning({
          content: '不能下载',
          duration: 10,
          closable: true
        })
      }
    },

    // 上传前文件
    handleBeforeUpload (file) {
      var str = file.name.substring(file.name.lastIndexOf('.'), file.name.length)
      if (['.xls', '.xlsx'].indexOf(str) == -1) {
        this.$Message.warning('仅支持上传xlsx文件')
        this.file = null
      } else {
        this.file = file
        console.log('file: ', this.file)
      }
      return false
    },

    // 上传成功
    uploadSuccess (res, row) {
      console.log('上传成功res: ', res)
      console.log('上传成功row: ', row)
      if (res.Code === 200 && res.Success) {
        this.fileObj = res.Data
        this.formData.annexId = res.Data.Id
      } else {
        this.$Message.error({
          content: res.message,
          duration: 10,
          closable: true
        })
      }
    },

    // 普通附件下载
    accessoryDownload (url) {
      console.log('下载url: ', url)
      window.open(url, '_blank')
    },

    // 移除附件
    removeFile () {
      this.fileObj = null
      this.formData.annexId = null
    },

    // 超过10M提示
    handleMaxSizeTen () {
      this.$Message.error({
        content: '您上传的文件太大，上传文件大小不能超过10M',
        duration: 10,
        closable: true
      })
    }
  }
}
</script>

<style lang="less" scope>
</style>
